//
//  WSColorImageView.m
//  1111
//
//  Created by iMac on 16/12/12.
//  Copyright © 2016年 zws. All rights reserved.
//

#import "JMPixelRGBExtractor.h"

@interface JMPixelRGBExtractor () {
    NSDictionary *colorToPointDict;
}

@property(nonatomic, strong) UIImageView *pickerImgv;

@end

@implementation JMPixelRGBExtractor

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.width)];
    if (self) {
        self.image = [self imageNamed:@"colorCircle"];
        self.userInteractionEnabled = YES;
        self.layer.cornerRadius = frame.size.width / 2;
        //self.layer.masksToBounds = YES;
        [self addSubview:self.pickerImgv];
        colorToPointDict = [[NSDictionary alloc] initWithDictionary:[self getNonTransparentPixelsToDic:[self imageNamed:@"colorCircle"]]];
    }
    return self;
}

#pragma mark -

- (NSBundle *)getSelfBundle {
    //TODO:注意Bundle名字需跟模块名称一致，否则会找不到path，直接Crash
    NSBundle *containnerBundle = [NSBundle bundleForClass:[self class]];
    return containnerBundle;
    /**
     *  注意
     *  在 podspec 文件中如果设置了spec.resource_bundles,则使用resourceBundle
     *  在 podspec 文件中如果设置了spec.resources,则使用containnerBundle
     */
    //NSBundle *resourceBundle = [NSBundle bundleWithPath:[containnerBundle pathForResource:@"JMPixelRGBExtractor" ofType:@"bundle"]];
    //return resourceBundle;
}

- (UIImage *)imageNamed:(NSString *)imageName {
    if (imageName.length == 0 || ![self getSelfBundle]) {
        return nil;
    }
    return [UIImage imageNamed:imageName inBundle:[self getSelfBundle] compatibleWithTraitCollection:nil];
}

#pragma mark - 懒加载

- (UIImageView *)pickerImgv {
    if (!_pickerImgv) {
        _pickerImgv = [UIImageView new];
        float w = 58 / 2;
        float h = 67 / 2;
        float x = self.frame.size.width / 2.0 - w / 2.0;
        float y = self.frame.size.height / 2.0 - h;
        _pickerImgv.frame = CGRectMake(x, y, w, h);
        _pickerImgv.image = [self imageNamed:@"colorPicker"];
    }
    return _pickerImgv;
}

#pragma mark - touchesEvent

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint pointL = [touch locationInView:self];

    if (pow(pointL.x - self.bounds.size.width / 2, 2) + pow(pointL.y - self.bounds.size.width / 2, 2) <= pow(self.bounds.size.width / 2, 2)) {
        UIColor *color = [self colorAtPixel:pointL];
        if (self.currentColorBlock) {
            self.currentColorBlock(color);
        }
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint pointL = [touch locationInView:self];

    if (pow(pointL.x - self.bounds.size.width / 2, 2) + pow(pointL.y - self.bounds.size.width / 2, 2) <= pow(self.bounds.size.width / 2, 2)) {
        UIColor *color = [self colorAtPixel:pointL];

        if (self.currentColorBlock) {
            self.currentColorBlock(color);
        }
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint pointL = [touch locationInView:self];

    if (pow(pointL.x - self.bounds.size.width / 2, 2) + pow(pointL.y - self.bounds.size.width / 2, 2) <= pow(self.bounds.size.width / 2, 2)) {
        UIColor *color = [self colorAtPixel:pointL];

        if (self.currentColorBlock) {
            self.currentColorBlock(color);
        }
    }
}

#pragma mark - setter

- (void)setColorDic:(NSDictionary *)colorDic {
    _colorDic = [[NSDictionary alloc] initWithDictionary:colorDic];

    int red = 0;
    int green = 0;
    int blue = 0;

    if (colorDic[@"Red"]) {
        red = [colorDic[@"Red"] intValue];
    }
    if (colorDic[@"Green"]) {
        green = [colorDic[@"Green"] intValue];
    }
    if (colorDic[@"Blue"]) {
        blue = [colorDic[@"Blue"] intValue];
    }

    NSString *colorString = [NSString stringWithFormat:@"%02X%02X%02X", red, green, blue];
    //NSLog(@"%@",colorToPointDict[colorString]);
    if (colorToPointDict[colorString]) {
        CGPoint point = [colorToPointDict[colorString] CGPointValue];
        float w = self.pickerImgv.frame.size.width;
        float h = self.pickerImgv.frame.size.height;
        self.pickerImgv.frame = CGRectMake(point.x - w / 2.0, point.y - h, w, h);

        /**
        UIColor *color = [self colorAtPixel:point];

        if (self.currentColorBlock) {
            self.currentColorBlock(color);
        }
         */
    }
}

- (void)setImage:(UIImage *)image {
    UIImage *temp = [self imageForResizeWithImage:image resize:CGSizeMake(self.frame.size.width, self.frame.size.height)];
    [super setImage:temp];
}

#pragma mark -

- (UIImage *)imageForResizeWithImage:(UIImage *)picture resize:(CGSize)resize {
    UIGraphicsBeginImageContextWithOptions(resize, NO, 1.0);  //设置缩放因子为1.0
    CGRect imageRect = CGRectMake(0.0, 0.0, resize.width, resize.height);
    [picture drawInRect:imageRect];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resizedImage;
}

//获取图片某一点的颜色
- (UIColor *)colorAtPixel:(CGPoint)point {
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.image.size.width, self.image.size.height), point)) {
        return nil;
    }

    NSInteger pointX = trunc(point.x);
    NSInteger pointY = trunc(point.y);
    CGImageRef cgImage = self.image.CGImage;
    NSUInteger width = self.image.size.width;
    NSUInteger height = self.image.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = {0, 0, 0, 0};
    CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);

    CGContextTranslateCTM(context, -pointX, pointY - (CGFloat)height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);

    NSLog(@"red = %f", (CGFloat)pixelData[0]);
    NSLog(@"green = %f", (CGFloat)pixelData[1]);
    NSLog(@"blue = %f", (CGFloat)pixelData[2]);

    CGFloat red = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

    float w = self.pickerImgv.frame.size.width;
    float h = self.pickerImgv.frame.size.height;
    self.pickerImgv.frame = CGRectMake(point.x - w / 2.0, point.y - h, w, h);

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

- (NSArray *)getNonTransparentPixelsToArr:(UIImage *)inputImg {
    NSMutableSet *colorSet = [NSMutableSet set];
    NSMutableArray *resultArray = [NSMutableArray array];

    CGImageRef cgImage = [inputImg CGImage];
    NSUInteger width = CGImageGetWidth(cgImage);
    NSUInteger height = CGImageGetHeight(cgImage);

    CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
    const unsigned char *pixels = CFDataGetBytePtr(data);

    for (NSUInteger x = 0; x < width; ++x) {
        for (NSUInteger y = 0; y < height; ++y) {
            NSUInteger pixelIndex = ((width * y) + x) * 4;
            int alpha = pixels[pixelIndex + 3];

            if (alpha > 0) {
                int red = pixels[pixelIndex];
                int green = pixels[pixelIndex + 1];
                int blue = pixels[pixelIndex + 2];

                NSString *colorString = [NSString stringWithFormat:@"%d%d%d", red, green, blue];

                if (![colorSet containsObject:colorString]) {
                    [colorSet addObject:colorString];

                    CGPoint point = CGPointMake(x, y);

                    NSDictionary *pixelColor = @{
                        @"Red" : @(red),
                        @"Green" : @(green),
                        @"Blue" : @(blue)
                    };

                    NSDictionary *pixelData = @{@"Position" : [NSValue valueWithCGPoint:point],
                                                @"Color" : pixelColor};

                    [resultArray addObject:pixelData];
                }
            }
        }
    }
    CFRelease(data);
    [colorSet removeAllObjects];  //Clear the color set

    return resultArray;
}

- (NSDictionary *)getNonTransparentPixelsToDic:(UIImage *)inputImg {
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];

    CGImageRef cgImage = [inputImg CGImage];
    NSUInteger width = CGImageGetWidth(cgImage);
    NSUInteger height = CGImageGetHeight(cgImage);
    float scale = self.frame.size.width / width * 1.0;

    CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
    const unsigned char *pixels = CFDataGetBytePtr(data);

    for (NSUInteger x = 0; x < width; ++x) {
        for (NSUInteger y = 0; y < height; ++y) {
            NSUInteger pixelIndex = ((width * y) + x) * 4;
            int alpha = pixels[pixelIndex + 3];

            if (alpha > 0) {
                int red = pixels[pixelIndex];
                int green = pixels[pixelIndex + 1];
                int blue = pixels[pixelIndex + 2];

                NSString *colorString = [NSString stringWithFormat:@"%02X%02X%02X", red, green, blue];

                CGPoint point = CGPointMake(x * scale, y * scale);
                mdic[colorString] = [NSValue valueWithCGPoint:point];
            }
        }
    }
    CFRelease(data);

    return mdic;
}

@end
